package top.hidoctor.auscultation.feature.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bigkoo.pickerview.view.TimePickerView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.tang.net.NetClient;
import com.tang.user.UserInfoManager;
import com.tang.util.AppUtil;
import com.tang.util.TimeUtil;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;
import com.zhihu.matisse.filter.Filter;
import com.zhihu.matisse.internal.entity.CaptureStrategy;
import com.zhihu.matisse.internal.entity.IncapableCause;
import com.zhihu.matisse.internal.entity.Item;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;

import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import io.reactivex.functions.Consumer;
import top.hidoctor.auscultation.R;
import top.hidoctor.auscultation.base.BaseActivity;
import top.hidoctor.auscultation.bean.JsonBean;
import top.hidoctor.auscultation.bean.PatientBean;
import top.hidoctor.auscultation.event.PatientEvent;
import top.hidoctor.auscultation.net.c.PatientDetailContract;
import top.hidoctor.auscultation.net.p.PatientDetailPresenter;
import top.hidoctor.auscultation.net.req.PatientReq;
import top.hidoctor.auscultation.utils.GetJsonDataUtil;
import top.hidoctor.auscultation.utils.GlideLoadEngine;
import top.hidoctor.auscultation.utils.IdentityUtils;
import top.hidoctor.auscultation.widget.GlideCircleTransform;

public class AddPatientActivity extends BaseActivity implements View.OnClickListener, PatientDetailContract.View {
    /**
     * 权限组
     */
    private static final String[] permissionsGroup = new String[]{
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA};
    private static final int IMAGE_PICK = 1000;
    TextView tvAddress, tvBrithday, tvGender;
    ArrayList<String> sexList = new ArrayList<>();
    private OptionsPickerView optionsPicker;
    private TimePickerView timePickerView;
    private ArrayList<JsonBean> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<JsonBean.CitiesBean>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<JsonBean.CitiesBean.CountiesBean>>> options3Items = new ArrayList<>();
    private Thread thread;
    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private static final int MSG_LOAD_FAILED = 0x0003;
    private String province;
    private String city;
    private String provinceId;
    private String cityId;
    private String area;
    private String areaId;
    private boolean isLoaded = false;
    private ImageView ivAvater;
    private EditText editName, editJianhuiren, editXiangxi, editPhone, editIdcard;
    private Button btnSave;
    private PatientDetailPresenter presenter;
    private PatientReq req;
    private RxPermissions rxPermissions;
    private String file = "";
    private RelativeLayout rlAvatar;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_add_patient);
        presenter = new PatientDetailPresenter(this, this);
        req = new PatientReq();
        initView();
        initEvent();
    }

    @Override
    public void onResume() {
        super.onResume();

    }

    private void initEvent() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                mHandler.sendEmptyMessage(MSG_LOAD_DATA);
            }
        }).start();
    }

    private void initView() {
        Toolbar toolbar = findViewById(R.id.toolbar);
        TextView tvTitle = findViewById(R.id.tv_title);
        toolbar.setNavigationIcon(R.mipmap.ic_back_left);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        tvTitle.setText("新建患者");
        btnSave = findViewById(R.id.btn_save);
        ivAvater = findViewById(R.id.iv_avater);
        tvAddress = findViewById(R.id.tv_address);
        tvBrithday = findViewById(R.id.tv_brithday);
        tvGender = findViewById(R.id.tv_gender);
        editName = findViewById(R.id.edit_name);
        editJianhuiren = findViewById(R.id.edit_jianhuren);
        editXiangxi = findViewById(R.id.edit_xiangxi);
        editPhone = findViewById(R.id.edit_phone);
        editIdcard = findViewById(R.id.edit_idcard);
        rlAvatar = findViewById(R.id.rl_avatar);


        sexList.add("男");
        sexList.add("女");
        //设置选中项文字颜色
        optionsPicker = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                tvGender.setText(sexList.get(options1));
            }
        })
                .setTitleText("选择性别")
                .setDividerColor(ContextCompat.getColor(AddPatientActivity.this, R.color.blue_main))
                .setTitleSize(18)
                .setContentTextSize(15)
                .setOutSideCancelable(true)
                .setSubmitColor(ContextCompat.getColor(AddPatientActivity.this, R.color.blue_main))
                .setCancelColor(ContextCompat.getColor(AddPatientActivity.this, R.color.colorHintText))
                .setTextColorCenter(ContextCompat.getColor(AddPatientActivity.this, R.color.blue_main)) //设置选中项文字颜色
                .build();
        optionsPicker.setPicker(sexList);

        Calendar selectedDate = Calendar.getInstance();
        Calendar startDate = Calendar.getInstance();
        //startDate.set(2013,1,1);
        Calendar endDate = Calendar.getInstance();
        //endDate.set(2020,1,1);

        startDate.set(1900, 0, 1);
        endDate.set(2021, 11, 31);

        timePickerView = new TimePickerBuilder(this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                tvBrithday.setText(TimeUtil.formatTime(date, TimeUtil.Y_M_D));
            }
        })
                .setTitleText("选择生日")
                .setType(new boolean[]{true, true, true, false, false, false})// 默认全部显示
                .setCancelText("取消")//取消按钮文字
                .setSubmitText("确定")//确认按钮文字
                .setContentTextSize(15)//滚轮文字大小
                .setSubCalSize(16)
                .setTitleSize(18)//标题文字大小
                .setOutSideCancelable(true)//点击屏幕，点在控件外部范围时，是否取消显示
                .isCyclic(false)//是否循环滚动
                .setDividerColor(ContextCompat.getColor(AddPatientActivity.this, R.color.blue_main))
                .setSubmitColor(ContextCompat.getColor(AddPatientActivity.this, R.color.blue_main))
                .setCancelColor(ContextCompat.getColor(AddPatientActivity.this, R.color.colorHintText))
                .setTextColorCenter(ContextCompat.getColor(AddPatientActivity.this, R.color.blue_main)) //设置选中项文字颜色
                .setDate(selectedDate)// 如果不设置的话，默认是系统时间*/
                .setRangDate(startDate, endDate)//起始终止年月日设定
                .setLabel("年", "月", "日", "时", "分", "秒")//默认设置为年月日时分秒
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .build();


        tvAddress.setOnClickListener(this);
        tvBrithday.setOnClickListener(this);
        tvGender.setOnClickListener(this);
        ivAvater.setOnClickListener(this);
        btnSave.setOnClickListener(this);
        rlAvatar.setOnClickListener(this);
        rxPermissions = new RxPermissions(this);

        editIdcard.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence pCharSequence, int pI, int pI1, int pI2) {

            }

            @Override
            public void onTextChanged(CharSequence pCharSequence, int pI, int pI1, int pI2) {
                // 键盘输入时的监听
                if (IdentityUtils.checkIDCard(pCharSequence.toString())) {
                    tvBrithday.setText(AppUtil.getBirthday(pCharSequence.toString()));
                } else {
                    tvBrithday.setText("无法识别");
                }

            }

            @Override
            public void afterTextChanged(Editable pEditable) {

            }
        });
    }

    /**
     * 点击事件
     * @param view
     */

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_gender:
                if (!AppUtil.isFastClick()) {
                    hideSoft(tvGender);
                    optionsPicker.show();
                }
                break;
            case R.id.tv_brithday:
                if (!AppUtil.isFastClick()) {
                    hideSoft(tvBrithday);
                    timePickerView.show();
                }
                break;
            case R.id.tv_address:
                hideSoft(tvAddress);
                if (isLoaded) {
                    showPickerView();
                } else {
                    Toast.makeText(AddPatientActivity.this, "Please waiting until the data is parsed", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.rl_avatar:
            case R.id.iv_avater:
                if (!AppUtil.isFastClick()) {
                    rxPermissions.request(permissionsGroup)
                            .subscribe(new Consumer<Boolean>() {
                                @Override
                                public void accept(Boolean aBoolean) throws Exception {
                                    if (aBoolean) {
                                        //申请的权限全部允许
                                        imagePick();
                                    } else {
                                        //只要有一个权限被拒绝，就会执行
                                        showToast("权限被禁止，无法打开相机、相册");
                                    }

                                }
                            });
                }
                break;
            case R.id.btn_save:
                if (!AppUtil.isFastClick()) {
                    //新建患者字段////1.选择头像（非必填）//2.姓名//3.性别//4.监护人//5.手机号（可是监护人手机号）//6.身份证（非必填）//7.出生日期//8.地区//9.详细地址（非必填）
                    String name = editName.getText().toString().trim();
                    String gender = tvGender.getText().toString().trim();
                    String jianhuiren = editJianhuiren.getText().toString().trim();
                    String phone = editPhone.getText().toString().trim();
                    String idCard = editIdcard.getText().toString().trim();
                    String brithday = tvBrithday.getText().toString().trim();
                    String address = tvAddress.getText().toString().trim();
                    String xiangxiAds = editXiangxi.getText().toString().trim();
                    if (TextUtils.isEmpty(name)) {
                        showToast("请输入患者姓名");
                        return;
                    }
                    if (TextUtils.isEmpty(gender)) {
                        showToast("请选择性别");
                        return;
                    }
                    if (TextUtils.isEmpty(jianhuiren)) {
                        showToast("请输入监护人姓名");
                        return;
                    }
                    if (TextUtils.isEmpty(phone)) {
                        showToast("请输入监护人手机号");
                        return;
                    }
//                    if (TextUtils.isEmpty(idCard)) {
//                        showToast("请输入身份证号");
//                        return;
//                    }
//                    if (!IdentityUtils.checkIDCard(idCard)) {
//                        showToast("请输入正确的身份号码");
//                        return;
//                    }
                    if (TextUtils.isEmpty(brithday)) {
                        showToast("请选择身份证号");
                        return;
                    }

//                    if (TextUtils.isEmpty(address)) {
//                        showToast("请选择地区");
//                        return;
//                    }
                    PatientReq req = new PatientReq();
                    req.setHospitalId(UserInfoManager.getInstance().getUserInfo().getHospitalId());
                    req.setAvatar(file);
                    req.setName(name);
                    req.setGuardian(jianhuiren);
                    req.setPhone(phone);
                    req.setIdCard(idCard);
                    req.setBirthday(brithday + " 00:00:00");
                    req.setGender(gender.equals("男") ? 1 : gender.equals("女") ? 2 : 0);
                    req.setAddress(address);
                    req.setDetailAddress(xiangxiAds);
                    presenter.addPatient(req);
                }
                break;

        }
    }

    private final int REQUEST_CODE_CHOOSE_PHOTO_ALBUM = 1;

    /**
     * 选择图片
     */
    private void imagePick() {
        Matisse.from(this)
                .choose(MimeType.ofImage(), false)
                .capture(true)
                .captureStrategy(new CaptureStrategy(true, "top.hidoctor.auscultation"))
                .theme(R.style.Matisse_Dracula)
                .countable(true)
                .maxSelectable(1)
                .addFilter(new Filter() {
                    @Override
                    protected Set<MimeType> constraintTypes() {
                        return new HashSet<MimeType>() {{
                            add(MimeType.PNG);
                        }};
                    }

                    @Override
                    public IncapableCause filter(Context context, Item item) {
                        try {
                            InputStream inputStream = getContentResolver().openInputStream(item.getContentUri());
                            BitmapFactory.Options options = new BitmapFactory.Options();
                            options.inJustDecodeBounds = true;
                            BitmapFactory.decodeStream(inputStream, null, options);
                            int width = options.outWidth;
                            int height = options.outHeight;

//                            if (width >= 500)
//                                return new IncapableCause("宽度超过500px");

                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                        }
                        return null;
                    }
                })
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
                .thumbnailScale(0.87f)
                .imageEngine(new GlideLoadEngine())
                .forResult(REQUEST_CODE_CHOOSE_PHOTO_ALBUM);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_CHOOSE_PHOTO_ALBUM && resultCode == RESULT_OK) {
            //图片路径 同样视频地址也是这个 根据requestCode
            List<String> pathList = Matisse.obtainPathResult(data);
            if (pathList.size() > 0) {
                RequestOptions optionsCircle = new RequestOptions();
                DrawableTransitionOptions transitionOptions = new DrawableTransitionOptions();
                Glide.with(mContext)
                        .load(pathList.get(0))
                        .apply(optionsCircle.transform(new GlideCircleTransform()).placeholder(R.drawable.ic_avater_zw))
                        .transition(transitionOptions.crossFade())
                        .into(ivAvater);
                presenter.uploadFile(pathList.get(0));
            }
        }
    }

    /**
     * 选择地址
     */
    private void showPickerView() {// 弹出选择器

        OptionsPickerView pvOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                if (options3Items.get(options1).get(options2).get(options3) != null) {
                    tvAddress.setText(options1Items.get(options1).getPickerViewText() + ","
                            + options2Items.get(options1).get(options2).getAreaName() + ","
                            + options3Items.get(options1).get(options2).get(options3).getAreaName());
                    provinceId = options1Items.get(options1).getAreaId();
                    cityId = options2Items.get(options1).get(options2).getAreaId();
                    areaId = options3Items.get(options1).get(options2).get(options3).getAreaId();

                } else {
                    tvAddress.setText(options1Items.get(options1).getPickerViewText() + ","
                            + options2Items.get(options1).get(options2).getAreaName());

                    provinceId = options1Items.get(options1).getAreaId();
                    cityId = options2Items.get(options1).get(options2).getAreaId();
                }
            }
        })

                .setTitleText("城市选择")
                .setDividerColor(Color.BLACK)
                .setTitleSize(18)
                .setContentTextSize(15)
                .setSubmitColor(ContextCompat.getColor(AddPatientActivity.this, R.color.blue_main))
                .setCancelColor(ContextCompat.getColor(AddPatientActivity.this, R.color.colorHintText))
                .setTextColorCenter(ContextCompat.getColor(AddPatientActivity.this, R.color.blue_main)) //设置选中项文字颜色
                .build();

        /*pvOptions.setPicker(options1Items);//一级选择器
        pvOptions.setPicker(options1Items, options2Items);//二级选择器*/
        pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
        pvOptions.show();
    }

    /***
     * handle 指令处理
     */
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_DATA:
                    if (thread == null) {//如果已创建就不再重新创建子线程了
//                        Toast.makeText(EditAddressActivity.this, "Begin Parse Data", Toast.LENGTH_SHORT).show();
                        thread = new Thread(new Runnable() {
                            @Override
                            public void run() {
                                // 子线程中解析省市区数据
                                initJsonData();
                            }
                        });
                        thread.start();
                    }
                    break;

                case MSG_LOAD_SUCCESS:
                    isLoaded = true;
                    break;

                case MSG_LOAD_FAILED:
                    Toast.makeText(AddPatientActivity.this, "Parse Failed", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

    /**
     * 解析数据
     */
    private void initJsonData() {//解析数据
        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */
        String JsonData = new GetJsonDataUtil().getJson(this, "city.json");//获取assets目录下的json文件数据

        ArrayList<JsonBean> jsonBean = parseData(JsonData);//用Gson 转成实体

        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = jsonBean;

        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            ArrayList<JsonBean.CitiesBean> CityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<JsonBean.CitiesBean.CountiesBean>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）

            for (int c = 0; c < jsonBean.get(i).getCities().size(); c++) {//遍历该省份的所有城市
                JsonBean.CitiesBean citiesBean = jsonBean.get(i).getCities().get(c);
                CityList.add(citiesBean);//添加城市
                ArrayList<JsonBean.CitiesBean.CountiesBean> City_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean.get(i).getCities().get(c).getAreaName() == null
                        || jsonBean.get(i).getCities().get(c).getCounties().size() == 0) {
                    City_AreaList.add(null);
                } else {
                    City_AreaList.addAll(jsonBean.get(i).getCities().get(c).getCounties());
                }
                Province_AreaList.add(City_AreaList);//添加该省所有地区数据
            }

            /**
             * 添加城市数据
             */
            options2Items.add(CityList);

            /**
             * 添加地区数据
             */
            options3Items.add(Province_AreaList);
        }
        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);

    }


    public ArrayList<JsonBean> parseData(String result) {//Gson 解析
        ArrayList<JsonBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                JsonBean entity = gson.fromJson(data.optJSONObject(i).toString(), JsonBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
            mHandler.sendEmptyMessage(MSG_LOAD_FAILED);
        }
        return detail;
    }

    @Override
    public void getDetailScu(PatientBean bean) {

    }

    @Override
    public void getUpadatDetailScu() {

    }

    @Override
    public void addPatientSuc() {
        showToast("新建患者成功！");
        //通知列表更新
        EventBus.getDefault().post(new PatientEvent());
        finish();
    }

    @Override
    public void getFileScu(String data) {
        this.file = data;
    }
}
